const mongoose = require('mongoose')
const Schema = mongoose.Schema   //声明Schema
let ObjectId = Schema.Types.ObjectId  //声明Object类型
const bcrypt = require('bcrypt')
const SALT_WORK_FACTOR = 10

// 用户注册时候的模型
const userSchema = new Schema ({
    userId: ObjectId,
    userName: {unique: true, type: String},
    passWord: String,
    createAt: {type: Date, default: Date.now()},
    lastLoginAt: {type: Date, default: Date.now()}
})

// 用户密码加密
userSchema.pre('save', function (next) {
    bcrypt.genSalt(SALT_WORK_FACTOR, (err, salt) => {
        if(err) {
            return
            next(err)
        }
        bcrypt.hash(this.passWord, salt, (err, hash) => {
            if(err){
                return
                next()
            }
            this.passWord = hash
            next()
        })
    })
})

// 实例比较密码
userSchema.methods = {
    comparePassword: (_passWord, passWord) => {
        return new Promise((resolve, reject) => {
            bcrypt.compare(_passWord, passWord, (err, isMatch) => {
                if(!err) resolve(isMatch)
                else reject(err)
            })
        })
    }
}

//发布模型
mongoose.model('User',userSchema)
